<?php

if(!defined('MAX_STR_IN_LIST')) define('MAX_STR_IN_LIST', 120);
class Component extends Object{
    
    protected $showlabel     = true;
    public    $list_in_table = false;
    protected $append_name = "";
    //protected $listActions = array('Veja Mais' => "show", 'Editar' => "edit", 'Excluir' => "apagar");
    protected $listActions = array('Veja Mais' => "show");
    public function __construct() {
        $this->LoadResource("html", "Html");
        $this->LoadResource('jqueryui/dialogs','cbox');
        $this->sfk = new ShowFk();
        $this->gui = new GUI();
        static $foo = 0;
        if($foo == 0) $this->js();
        $foo = 1;
    }
    
    public function addListAction($name, $link){
        $this->listActions[$name] = $link;
    }
    
    public function removeListAction($name){
        if(isset($this->listActions[$name])) unset($this->listActions[$name]);
    }
    
    protected function LoadCss($model){
        
        $temp = explode("/", $model);
        $csss[] = str_replace("_", "/", $model);
        $csss[] = array_shift($temp);
        $csss[] = 'component';
        foreach($csss as $css)
            if($this->Html->loadCssIfExists($css) !== false) return $css;
    }

    protected $showOnlyListItem = false;
    public function showOnlyListItem(){
        $this->showOnlyListItem = true;
    }

    private $dados = array();
    public function listar($model, $itens, $title = "", $class = ''){
        if($this->list_in_table){
            $this->listInTable($model, $itens, $title, $class);
            return;
        }
        $this->LoadModel($model, 'obj');
        $dados = $this->obj->getDados();
        $this->dados = $dados;
        
        $addclass = $this->getEnumClasses($dados);
        $pkey = $this->obj->getPkey();
        $id = str_replace("/", "_", $model);
        $class = ($class != "")? " class='$class'":"";
        $display = (is_array($itens) && !empty ($itens));
        if(!$this->showOnlyListItem){
            echo "<div$class> ";
                if(!empty($itens)) $this->gui->title($title);
                echo "<ul id='$id' class='list'>";
        }
        if($display){
                foreach($itens as $item){
                    if(!$this->pode_exibir($model, $item)) continue;
                    $class = $this->getEnumClass($addclass, $item);
                    echo "<li class='list-item list_$id $class'>";
                        $this->DrawItem($model, $pkey, $item, $dados);
                    echo "</li>";
                }
        }
        
        $this->print_paginator_if_exists($this->obj);
        if(!$this->showOnlyListItem){
                echo "</ul>";
            echo "</div>";     
        }
    }
    
    protected function getEnumClasses($dados){
        $addclass = array();
        foreach($dados as $nm => $d){
            if(array_key_exists('type', $d) && $d['type'] == 'enum'){
                $addclass[] = $nm;
            }
        }
        return $addclass;
    }
    
    protected function getEnumClass($addclass, $item){
        $class = "";
        if(!empty($addclass)){
            foreach($addclass as $var){
                if(array_key_exists($var, $item)){
                    $class .= " ".$item[$var];
                }
            }
        }
        return $class;
    }
    
    protected function print_paginator_if_exists($obj){
        $model = $obj->getTable();
        $v = EventTube::getRegion("paginate_$model");
        if(empty($v)) return;
        $v = array_shift($v);
        echo $v;
    }


    public function listInTable($model, $itens, $title = "", $class = ''){
        
        $this->LoadModel($model, 'obj');
        $dados = $this->obj->getDados();
        $pkey = $this->obj->getPkey();
        $id = str_replace("/", "_", $model);
        $class = ($class != "")? " class='$class'":"";
        $addclass = $this->getEnumClasses($dados);
        $table  = array();
        $i      = 0;
        $header = array();
        $stopheader = false;
        if(!empty($itens)){
            foreach($itens as $item){
                $tb = array();
                if(!$this->pode_exibir($model, $item)) continue;
                foreach($item as $name => $valor){
                    if($this->checkIsPrivate($dados, $name)) continue;
                    if(!$stopheader) $header[] = array_key_exists($name, $dados)?$dados[$name]['name']:$name;
                    $val = $this->formatType($name, $dados, $valor);
                    $tb[$name] = $val;
                }
                $links = $this->getActionLinks($model, $pkey, $item);
                if(!MOBILE){
                    $tb["Ações"] = (is_array($links))? implode(" ", $links):"";
                    if(!$stopheader) {
                        if($tb["Ações"] != "" && !MOBILE){
                            $header[] = "Ações";
                        }
                    }
                    if($tb["Ações"] == "") unset($tb["Ações"]);
                }
                else $tb['__link'] = $links;
                
                $tb["__id"]  = implode("-", $this->getPkeyValue($pkey, $item));
                $tb["__class"] = $this->getEnumClass($addclass, $item);
                
                $table[$i] = $tb;
                $i++;
                $stopheader = true;
            }
        }
        echo "<div$class id='$id'> ";
            $this->gui->subtitle($title);
            $this->LoadResource('html/table', 'tb');
            $this->tb->draw($table, $header);
            $this->print_paginator_if_exists($this->obj);
        echo "</div>";
    }
    
    protected function DrawItem($model, $pkey, $item, $dados){
        
        if(empty ($item)) return;
        if(!$this->pode_exibir($model, $item)) return;
        $links = $this->getActionLinks($model, $pkey, $item);
        
        $lini = $linf = "";
        if(MOBILE){
            $url = $this->Html->getLink($links);
            $lini = "<a href='$url'>";
            $linf = "</a>";
            $link = "";
        }
        else $link  = (is_array($links))? implode(" ", $links):"";
        
        echo "<div class='container'>$lini";
        foreach($item as $name => $it){
            if($this->checkIsPrivate($dados, $name)) {continue;}
            $it = $this->formatType($name, $dados, $it);
            if(is_array($it) && isset($dados[$name]['fkey'])){
                 $this->LoadComponent($dados[$name]['fkey']['model'], 'md');
                 $this->md->listar($dados[$name]['fkey']['model'], $it);
            }elseif(!is_array($it)) 
                echo "<span class='$name'>$it</span>";
            else $this->show($model, $it);
        }
        echo "$link $linf </div>";
    }
    
    protected function checkIsPrivate($dados, $name){
        if(@$name[0] == "_" && @$name[1] == "_") return true;
        if(!array_key_exists($name, $dados)) return false;
        if(array_key_exists('private', $dados[$name]) && $dados[$name]['private'] == true ) return true;
        if(array_key_exists('mobile_hide', $dados[$name]) && $dados[$name]['mobile_hide'] == true && MOBILE == true) return true;
        return false;
    }
    
    protected function getActionLinks($model, $pkey, $item){
        $pkey = implode("/",$this->getPkeyValue($pkey, $item));
        if(MOBILE){
            $var = $this->Html->getActionLinkIfHasPermission("$model/show/$pkey", "");
            return ($var != "")? "$model/show/$pkey":"";
        }
        $v = array();
        foreach($this->listActions as $name => $action){
            
            $class = GetPlainName($action);
            $link = (strstr($action, "/") === false)?"$model/$action/$pkey":"$action/$pkey";
            $link = $this->Html->getActionLinkIfHasPermission($link, "$name",$class, "");
            if($link == "") continue;
            $v[$name] = $link;
            //$url      = $this->Html->getLink("$model/$action/$pkey"  , "$name",$class, "");
            //$v[$name] = "<a href='$url' class='action_perm $class'>$name</a>";
        }
        return($v);
    }
    
    protected function gerarLink($model, $pkey, $item){
        $pkey = implode("/",$this->getPkeyValue($pkey, $item));
        return $this->Html->getLink("$model/show/$pkey");
    }
    
    protected function getPkeyValue($pkey, $item){
        $out = array();
        if(is_array($pkey)){
            foreach($pkey as $pk){
                if(isset($item["__$pk"])) $out[] = $item["__$pk"];
                elseif(isset($item[$pk])) $out[] = $item[$pk];
            }
        }elseif(isset($item[$pkey])) $out[] = $item[$pkey];
        return $out;
    }
    
    public function formatType($name, $dados, $valor){
        if(method_exists($this, "format_$name")) {
            $method = "format_$name";
            return trim($this->$method($valor, $dados));
        }
        if(!array_key_exists($name, $dados)) {if(!is_array ($valor))return trim($valor); else return $valor;}
        if(!array_key_exists('type', $dados[$name])){
            return is_array($valor) ? $valor: trim($valor);
        }
        if(is_array($valor)) return $valor;
        
        switch ($dados[$name]["type"]){
            case 'date':
                if($valor == '0000-00-00') return "";
                $valor = timeResource::Date2StrBr($valor, false);
                break;
            case 'datetime': 
            case 'timestamp': 
                if($valor == '0000-00-00' || $valor == '0000-00-00 00:00:00') return "";
                $valor = timeResource::Date2StrBr($valor);
                break;
            case 'text':
            case 'varchar':
                $valor = strip_tags($valor, "<b><a><ul><li><ol><i><u>");
                if(strlen($valor) <= MAX_STR_IN_LIST) break;
                $valor = Resume($valor, MAX_STR_IN_LIST);
                break;
            case 'bit': 
                $valor = ($valor == 1 || $valor === true)?"Sim":"Não";
                break;
            case 'enum':
                $valor = (isset($dados[$name]['options'][$valor]))?$dados[$name]['options'][$valor]: ucfirst($valor);
                break;
        }
        return trim($valor);
    }
    
    public function form($model, $values = array(), $ajax = true, $url = ""){
        $this->LoadResource('formulario', 'form');
        $url = ($url == "")?"$model/formulario":$url;
        $this->LoadModel($model, 'md');
        $dados = $this->md->getDados();
        $this->form->NewForm($dados, $values, array(), $ajax, $url);
    }
    
    public function show($model, $item){
        if(!is_array($item) ||empty ($item)) return;
        if(!$this->pode_exibir($model, $item)){
            $this->conteudo_bloqueado();
            return;
        }
        $this->LoadModel($model, 'obj');
        $dados = $this->obj->getDados();
        if(empty ($dados)) throw new ComponentException(
            __CLASS__, 
            "O Modelo $model não foi configurado corretamente e está vazio"
        );
        
        $this->dados = $dados;
        $this->drawTitle($item);
        
        $id = str_replace("/", "_", $model);
        echo "<div id='$id'>"; 
        foreach($item as $name => $var){
            if(array_key_exists($name, $dados)){
                $arr = $dados[$name];
                if(array_key_exists("fkey", $arr))
                    $var = $this->sfk->exibir($arr, $var, $name);
            }else $arr = array();
            $this->DrawShowItem($name, $var, $arr);
        }
            
        echo "</div><div class='clear'></div>";
    }
    
    private function drawTitle(&$item){
        $title = $subtitle = "";
        foreach($this->dados as $name => $var){
            if(array_key_exists('title', $var))        $title    = $name;
            elseif(array_key_exists('subtitle', $var)) $subtitle = $name;
        }
        
        if($title != "" || $subtitle != ""){
            echo "<hr/>";
            if(isset($item[$title]))    { $this->gui->subtitle($item[$title]);     unset($item[$title]);}
            if(isset($item[$subtitle])) { $this->gui->infotitle($item[$subtitle]); unset($item[$subtitle]);}
            echo "<hr/>";
        }
    }
    
    public function getFkeyLink($fkmodel, $fkeyarr){
        $md_var = isset($fkeyarr['dstmodel'])?$fkeyarr['dstmodel']:"";
        $md_link = ($md_var != "")? $md_var: $fkmodel;
        
        $id_model = str_replace("/", "_", $fkmodel);
        $append = $this->Html->getActionLinkIfHasPermission("$md_link/formulario/ajax", "[+]");
        if($append!= ""){
            $append = $this->Html->MakeLink("#$id_model", "[+]", "lk_$id_model");
            $this->cbox->formDialog(".lk_$id_model", $fkmodel);
        }
        return $append;
    }
    
    public function drawDestaque(&$item, $title, $description, $extra = "", $separator = true){
        if($separator) echo "<hr/>";
        if(isset($item[$title]))      { 
            $item[$title] = $this->formatType($title, $this->dados, $item[$title]); 
            $this->gui->subtitle($item[$title]);
            unset($item[$title]);
        }
        if(isset($item[$description])){ 
            $item[$description] = $this->formatType($description, $this->dados, $item[$description]);
            $this->gui->infotitle($item[$description]);
            unset($item[$description]);
        }
        if(isset($item[$extra])){
            $item[$extra] = $this->formatType($extra, $this->dados, $item[$extra]);
            $this->gui->paragraph($item[$extra]); 
            unset($item[$extra]);
        }
        if($separator) echo "<hr/>";
    }
    
    protected function DrawShowItem($name, $var, $arr){
        if($this->checkIsPrivate(array($name => $arr), $name)) return;
        if(@$name[0] == "_" && @$name[1] == "_") return;
        if(@$name[0] == "_" && @$name[1] == "_") return;
        if(array_key_exists('type', $arr)){
            $type = $arr['type'];
            switch ($type){
                case 'date':
                    if($var == '0000-00-00' || $var == '0000-00-00 00:00:00'){ $var = ""; }
                    else $var = timeResource::Date2StrBr($var, false);
                    break;
                case 'datetime': 
                case 'timestamp': 
                    if($var == '0000-00-00' || $var == '0000-00-00 00:00:00'){ $var = ""; }
                    else $var = timeResource::Date2StrBr($var);
                    break;
                case 'bit': 
                    $var = ($var == 1 || $var === true)?"Sim":"Não";
                    break;
            }
        }
        if(!is_array($var)) $var = trim($var);
        
        if($var == "" || empty($var)) return;
        echo "<span id='$name' class='c_item'>";
        
        $this->drawLabel($arr, $name);
        
        if(is_array($var)){
            $t = "";
            foreach($var as $v){
                echo "$v$t";
                $t = " - ";
            }
        }
        else echo "<span class='c_description'>$var</span>";
        //else echo "<span class='c_description' contenteditable='true'>$var</span>";
        echo "</span>";
    }
    
    public function drawLabel($arr, $name){
        if(!$this->showlabel) return;
        if(isset($arr['hidelabel']) && $arr['hidelabel'] == true) return;
        $label = (array_key_exists('name', $arr))?$arr['name']:ucfirst ($name);
        echo "<h4 class='label'>$this->append_name $label</h4>";
        $this->append_name = "";
    }


    protected function n1info($title, $link, $chave){
        $cod  = array_keys($chave); $cod = array_shift($cod);
        $nome = array_shift($chave);
        $link = $this->Html->getLink($link."/$cod/".GetPlainName($nome));
        $this->gui->info("$title: <a href='$link'>$nome</a><br/>");
    }
        
    protected function linksnav($links){
        if(!is_array($links) || empty ($links)) return;
        
        $total = count($links);
        $i = 0;
        foreach($links as $title => $url){
            if(++$i == $total) {
                echo $title;
                return;
            }
            $link = $this->Html->getLink($url);
            echo "<a href='$link'>$title</a> > ";
        }
        
    }
    
    protected function pode_exibir($model, $item){
        $exibir = "__".str_replace("/", "_", $model) . "_exibir";
        if(!array_key_exists($exibir, $item)) return true;
        if($item[$exibir] != 'esconder') return true;
        
        $this->LoadModel('usuario/login', 'uobj');
        if(!$this->uobj->IsLoged()) return false;
        if(!$this->uobj->UserIsAdmin()) return false;
        $this->gui->info("Este conteúdo está bloqueado para a exibção ");
        return true;
    }
    
    protected function conteudo_bloqueado(){
        echo "<hr />";
        $this->gui->title("Conteúdo bloqueado");
        $this->gui->subtitle("Este conteúdo foi bloqueado pelo administrador para edição.");
        echo "<hr />";
    }
    
    protected function js(){
        static $js = 0;
        if($js == 1) {return;}
        $this->Html->LoadJs(URL .'/static/js/lib/component/usability');
        $js = 1;
    }
    
    protected function AddItem($link, $html, $class){
        if($html == "") return;
        $this->gui->opendiv("", $class);
        $link = $this->Html->getLink($link);
        echo "<a href='$link' style='display:block; height:100%;'>$html</a>";
        $this->gui->closediv();
    }
}

?>
